from socket import socket, AF_INET, SOCK_STREAM
import select, sys

tcp_server = socket(AF_INET, SOCK_STREAM)
server_addr = ('', 2000)
tcp_server.bind(server_addr)
tcp_server.listen(10)

epoll = select.epoll()
epoll.register(sys.stdin.fileno(),select.EPOLLIN)
epoll.register(tcp_server.fileno(),select.EPOLLIN)
while True:
    event_list=epoll.poll(-1)
    for fd,event in event_list:
        if fd==tcp_server.fileno():
            client_soket, client_adddr = tcp_server.accept()
            print(client_adddr)
            epoll.register(client_soket.fileno(),select.EPOLLIN)
        elif fd==sys.stdin.fileno():
            data = input()
            client_soket.send(data.encode('utf8'))
        elif fd==client_soket.fileno():
            recv_data = client_soket.recv(1000)
            if recv_data:
                print(recv_data.decode('utf8'))
            else:
                print('对方断开')
                epoll.unregister(client_soket.fileno())
                client_soket.close()
                break
